package cn.openea.perpartner.mpwx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.common.log.factory.AsyncFactory;
import cn.openea.perpartner.mpwx.core.WxServiceTemplate;
import cn.openea.perpartner.mpwx.service.IWxMpSyncService;
import cn.openea.perpartner.system.entity.SysUser;
import cn.openea.perpartner.system.enums.AppletsEnums;
import cn.openea.perpartner.system.service.ISysConfigService;
import cn.openea.perpartner.system.service.ISysUserService;
import cn.openea.perpartner.system.util.ToolsUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.StringJoiner;

/**
 * @author Weird077
 * @description 关注公众号时尝试完成关联用户基本信息, 主要对从小程序先注册 sys_user 表中完善关联公众号的信息
 * @date 2022-06-23 23:19
 */
@Service
public class WxMpSyncServiceImpl implements IWxMpSyncService {
    /**
     * WxServiceInf
     */
    @Autowired
    private WxServiceTemplate wxServiceTemplate;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;

    @Override
    public String run(HashMap<String, Object> params) {
        String myOpenId = (String) params.get("fromUserName");
        String userId = (String) params.get("userId");
        try {
            // 获取access_token
            WxMpService wxMpService = wxServiceTemplate.getWxMpService();
            // 获取用户基本信息
            WxMpUser wxMpUser = wxMpService.userInfo(myOpenId, null);
            // unionId
            String unionId = wxMpUser.getUnionId();
            if (StrUtil.isBlank(unionId)) {
                return "";
            }
            //查询用户表用户是否注册
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getUnionid, unionId);
            SysUser user = userService.getOne(wrapper);
            // 用户不存在, 则创建用户
            if (BeanUtil.isEmpty(user)) {
                user = new SysUser();
                user.setUnionid(unionId);
                user.setMyopenid(myOpenId);
                user.setUserid(StrUtil.isBlank(userId)? ToolsUtil.autoUserID() :userId);
                user.setPassword(BCrypt.hashpw("openeapass", BCrypt.gensalt()));
                user.setStepstatus("3");
            } else {
                // 更新用户已关注公众号标识
                StringJoiner joiner = new StringJoiner(",");
                joiner.add(user.getStepstatus());
                user.setStepstatus(joiner.toString());
            }
            if (StrUtil.isBlank(user.getMyopenid())) {
                user.setMyopenid(myOpenId);
            }
            // 初始化其它的参数
            if (StrUtil.isNotBlank(wxMpUser.getNickname())) {
                user.setNickname(wxMpUser.getNickname());
            }
            if (StrUtil.isNotBlank(wxMpUser.getHeadImgUrl())) {
                user.setAvatar(wxMpUser.getHeadImgUrl());
            }
            if (StrUtil.isNotBlank(wxMpUser.getSex())) {
                user.setSex(wxMpUser.getSex());
            }
            if (StrUtil.isNotBlank(wxMpUser.getCountry())) {
                user.setCountry(wxMpUser.getCountry());
            }
            if (StrUtil.isNotBlank(wxMpUser.getProvince())) {
                user.setProvince(wxMpUser.getProvince());
            }
            if (StrUtil.isNotBlank(wxMpUser.getCity())) {
                user.setCity(wxMpUser.getCity());
            }
            user.setIsSubscribed("1");
            userService.saveOrUpdate(user);
            user.setAppletId(AppletsEnums.MEILY.getAppletId());
            userService.updateUserCache(user);
            //同步用户到bpm
            String url = configService.selectConfigByKey(AppletsEnums.MEILY.getAppletId()+".account.async.url");
            if(StrUtil.isNotBlank(url)){
                JSONObject wxObject = new JSONObject();
                wxObject.put("userid",user.getUserid());
                wxObject.put("subscriptionOpenid",user.getMyopenid());
                wxObject.put("stepStatus",user.getStepstatus());
                wxObject.put("unionid",user.getUnionid());
                wxObject.put("avatar",user.getNickname());
                wxObject.put("nickname",user.getNickname());
                wxObject.put("isSubscribed",user.getIsSubscribed());
                BeanUtil.copyProperties(user,wxObject,false);
                AsyncManager.me().execute(AsyncFactory.asyncBpmOrg(url,wxObject));
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "";
    }

}
